<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="pagerequest.keyword"
        :placeholder="L('UserName')+'/'+L('Name')"
        style="width: 200px;"
        class="filter-item"
      />
      <el-select
        v-model="activeSelected"
        :placeholder="L('Select')"
        clearable
        style="width: 90px"
        class="filter-item"
        @change="isActiveChange"
      >
        <el-option
          :label="L('All')"
          value="All"
        />
        <el-option
          :label="L('Actived')"
          value="Actived"
        />
        <el-option
          :label="L('NoActive')"
          value="NoActive"
        />
      </el-select>
      <el-date-picker
        v-model="creationTime"
        class="filter-item"
        type="daterange"
        align="right"
        unlink-panels
        start-placeholder="创建开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="getpage"
      >
        {{ L('Find') }}
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="create"
      >
        {{ L('Add') }}
      </el-button>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="tableSortChange"
      >
        <el-table-column
          prop="userName"
          :label="L('UserName')"
          width="180"
        />
        <el-table-column
          prop="emailAddress"
          :label="L('EmailAddress')"
        />
        <el-table-column :label="L('IsActive')">
          <template slot-scope="{row}">
            <el-tag :type="row.isActive | statusFilter">
              {{ row.isActive ? L('Yes') : L('No') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          sortable="custom"
          prop="creationTime"
          :label="L('CreationTime')"
        >
          <template slot-scope="{row}">
            <span>{{ row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="L('LastLoginTime')">
          <template slot-scope="{row}">
            <span>{{ row.lastLoginTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="L('Actions')">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              @click="edit(scope.row)"
            >{{ L('Edit') }}</el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteUser(scope.row)"
            >{{ L('Delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="datatable-paging">
      <el-pagination
        :page-sizes="[10, 50, 100, 150]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="pagesizeChange"
        @current-change="pageChange"
      />
    </div>

    <user-edit-dialog
      ref="userdialog"
      @save-success="getpage"
    />
  </div>
</template>

<script>
import userDialog from './user-edit-dialog'
import waves from '@/directive/waves' // waves directive
import PagedFilterAndSortedRequest from '@/store/entities/pagedFilterAndSortedRequest'
import { parseTime } from '@/utils'

export default {
  name: 'Users',
  components: { 'user-edit-dialog': userDialog },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      pagerequest: {
        keyword: null,
        isActive: null,
        from: null,
        to: null,
        ...PagedFilterAndSortedRequest
      },
      activeSelected: null,
      creationTime: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      editUser: {}
    }
  },
  computed: {
    list() {
      return this.$store.state.user.list
    },
    totalCount() {
      return this.$store.state.user.totalCount
    },
    currentPage() {
      return this.$store.state.user.currentPage
    },
    pageSize() {
      return this.$store.state.user.pageSize
    },
    loading() {
      return this.$store.state.user.loading
    }
  },
  async created() {
    this.getpage()
    await this.$store.dispatch({
      type: 'user/getRoles'
    })
  },
  methods: {
    tableSortChange(column) {
      this.pageChange(1)
      if (column.order === 'descending') {
        this.pagerequest.sorting = `${column.prop} desc`
      } else {
        this.pagerequest.sorting = `${column.prop} asc`
      }
      this.getpage()
    },
    edit(row) {
      this.$refs.userdialog
        .open(row, 'edit')
        .then(async result => {
          // await this.getpage()
        })
        .catch(err => {
          console.log(err)
        })
    },
    create() {
      this.$refs.userdialog
        .open({ isActive: true, roleNames: [] }, 'create')
        .then(async result => {
          // await this.getpage()
        })
        .catch(err => {
          console.log(err)
        })
    },
    isActiveChange(val) {
      console.log(val)
      if (val === 'Actived') {
        this.pagerequest.isActive = true
      } else if (val === 'NoActive') {
        this.pagerequest.isActive = false
      } else {
        this.pagerequest.isActive = null
      }
    },
    async deleteUser(row) {
      this.$confirm(this.L('DeleteUserConfirm'), this.L('Tips'), {
        confirmButtonText: this.L('Yes'),
        cancelButtonText: this.L('No'),
        type: 'warning'
      })
        .then(async() => {
          await this.$store.dispatch({
            type: 'user/delete',
            data: row
          })
          await this.getpage()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    pageChange(page) {
      this.$store.commit('user/SET_CURRENT_PAGE', page)
      this.getpage()
    },
    pagesizeChange(pagesize) {
      this.$store.commit('user/SET_PAGE_SIZE', pagesize)
      this.getpage()
    },
    async getpage() {
      this.pagerequest.maxResultCount = this.pageSize
      this.pagerequest.skipCount = (this.currentPage - 1) * this.pageSize
      // filters
      if (this.creationTime.length > 0) {
        this.pagerequest.from = parseTime(this.creationTime[0], '{y}-{m}-{d}')
      }
      if (this.creationTime.length > 1) {
        this.pagerequest.to = parseTime(this.creationTime[1], '{y}-{m}-{d}')
      }

      await this.$store.dispatch({
        type: 'user/getAll',
        data: this.pagerequest
      })
    }
  }
}
</script>

<style>
</style>
